import Assert from "./Assert";

export default function extendContext(app){
    let props={
        jsonp:function(body){
            if (body==null){
                body="null";
            }else if (typeof body==='object'){
                body=JSON.stringify(body);
            }
            let callback=this.request.query.callback;
            if (callback&&callback.match(/^\w+$/)){
                this.response.type='text/javascript';
                this.body=callback+"("+body.toString()+")";
                this.sent=true;
            }else{
                this.response.type='application/json';
                this.body=body.toString();
                this.sent=true;
            }
        },
        success(data){
            if (!this.sent){
                if (data&&data.success!=null){
                    this.jsonp(data);
                }else{
                    this.jsonp({success:true,data})
                }
            }
        },
        fail(message){
            this.jsonp({success:false,message:message})
        },
        params(){
            return Object.assign({},this.request.params,this.request.query,this.request.body)
        },
        param(name,defaultValue){
            return this.request.params&&this.request.params[name]
                ||this.request.query&&this.request.query[name]
                ||this.request.body&&this.request.body[name]
                ||defaultValue;
        }
    };
    for (let i in props){
        app.context[i]=props[i];
    }

    Object.defineProperties(app.context,{
       assert:{
           get:function(){
               if (this.__assert==null){
                   this.__assert=new Assert(this);
               }
               return this.__assert;
           }
       }
    });
}